#include "DroneManager.h"

// Constructor
DroneManager::DroneManager() {
	this->head = NULL;
}

// Deconstructor
DroneManager::~DroneManager() {
	Drone *slider = this->head;

	while(slider) {
		Drone *tmp = slider;

		slider = slider->next;

		delete tmp;
	}
}


// Manage a new drone
bool DroneManager::add(Connection* conn) {
	Drone *addme = new Drone(conn);

	// prepend drone to head of list
	if(this->head == NULL) {
		this->head = addme;
	}
	else {
		addme->next = this->head;
		this->head->prev = addme;
		this->head = addme;
	}

	return true;
}

// Delete a Drone
bool DroneManager::del(Drone *drone) {
	Drone *slider = this->head;

	while(slider) {
		if(slider == drone) {
			// Drone identified
			if(slider->prev) {
				if(slider->next) {
					slider->prev->next = slider->next;
				}
				else {
					slider->prev->next = NULL;
				}
			}
			if(slider->next) {
				if(slider->prev) {
					slider->next->prev = slider->prev;
				}
				else {
					slider->next->prev = NULL;
				}
			}
			// fix head node if we are deleting it
			if(slider == this->head) {
				this->head = slider->next;
				if(this->head) {
					this->head->prev = NULL;
				}
			}

			// free up resources
			delete slider;

			break;
		}

		slider = slider->next;
	}

	return true;
}
